﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Anay.TaskScheduling.Common;
using Anay.TaskScheduling.JobConfig;

namespace Anay.TaskScheduling
{
    public partial class TaskConfig : Form
    {
        IConfigHelper configHelper = new ConfigFactory().GetInstance();
        public TaskConfig()
        {
            InitializeComponent();
            RefreshConfigTree();
            InitDropList();

        }

        /// <summary>
        /// 初始化配置树
        /// </summary>
        public void RefreshConfigTree()
        {

            var configiList = configHelper.GetAllList();
            if (configiList.Count <= 0)
            {
                MessageBox.Show(@"没有找到配置文件'Task_config.json'");
                return;
            }
            configTree.Nodes.Clear();
            foreach (var item in configiList)
            {
                TreeNode node = new TreeNode()
                {
                    Text = string.Format("({0}){1}", item.Id, item.JobName),
                    Name = item.Id
                };
                if (item.IsEnabled == "0")
                {
                    node.ForeColor = Color.Green;//启用绿色
                }
                else
                {
                    node.ForeColor = Color.Red;//未启用红色
                }

                configTree.Nodes.Add(node);
            }
        }


        /// <summary>
        /// 在线Cron表达式生成器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("IExplore", "http://cron.qqe2.com/");
        }

        /// <summary>
        /// 填写规则展示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show(@"
            {
              'Id': '001',唯一
              'JobName': '任务名称',
              'TimeType': 'tigger-秒  runner-crob表达式 ',
              'TimeExpression': '定时时间',
              'IsEnabled': '0-启用 1-不启用',
              'JobUrl': '执行地址url',
              'Metthod':  '访问url的方法 Get/Post'
              'JsonString'：'访问urlPost传递的参数 json对象的字符串'
            }", "填写规则");
        }

        /// <summary>
        /// 配置树节点节点点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            var node = e.Node;
            if (node != null)
            {
                var config = configHelper.GetTask_config(node.Name);
                if (config != null)
                {
                    Id.ReadOnly = true;
                    Id.Text = config.Id;
                    JobName.Text = config.JobName;
                    TimeType.SelectedValue = config.TimeType;
                    TimeExpression.Text = config.TimeExpression;
                    IsEnabled.SelectedValue = config.IsEnabled;
                    JobUrl.Text = config.JobUrl;
                    Method.SelectedValue = config.Metthod;
                    JsonString.Text = config.JsonString;
                }
            }
        }

        /// <summary>
        /// 清空文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, EventArgs e)
        {
            ClearInput();
        }

        public void ClearInput()
        {
            Id.ReadOnly = false;
            Id.Text = string.Empty;
            JobName.Text = string.Empty;
            TimeType.SelectedValue = string.Empty;
            TimeExpression.Text = string.Empty;
            IsEnabled.SelectedValue = string.Empty;
            JobUrl.Text = string.Empty;
            Method.SelectedValue = string.Empty;
            JsonString.Text = string.Empty;
        }

        public void InitDropList()
        {
            List<object> timeTypeList = new List<object>()
            {
                new{ Text="tigger(秒)",Value="tigger"},
                new{ Text="runner(表达式)",Value="runner"}
            };
            TimeType.DataSource = timeTypeList;
            TimeType.DisplayMember = "Text";
            TimeType.ValueMember = "Value";

            List<object> isEnabledList = new List<object>()
            {
                new{ Text="启用",Value="0"},
                new{ Text="停止",Value="1"}
            };
            IsEnabled.DataSource = isEnabledList;
            IsEnabled.DisplayMember = "Text";
            IsEnabled.ValueMember = "Value";


            List<object> methodList = new List<object>()
            {
                new{ Text="GET",Value="Get"},
                new{ Text="POST",Value="Post"}
            };
            Method.DataSource = methodList;
            Method.DisplayMember = "Text";
            Method.ValueMember = "Value";

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, EventArgs e)
        {
            var id = Id.Text;
            configHelper.DeleteConfig(id);
            RefreshConfigTree();
            ClearInput();

        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, EventArgs e)
        {
            if (Id.ReadOnly)
            {
                //修改
                var config = configHelper.GetTask_config(Id.Text);
                if (configHelper.GetTask_config(Id.Text) == null)
                {
                    MessageBox.Show("该任务已经不存在了，无法修改");
                    return;
                }
                config.JobName = JobName.Text;
                config.TimeType = TimeType.SelectedValue.ToString();
                config.TimeExpression = TimeExpression.Text;
                config.IsEnabled = IsEnabled.SelectedValue.ToString();
                config.JobUrl = JobUrl.Text;
                config.Metthod = Method.SelectedValue.ToString();
                config.JsonString = JsonString.Text;
                configHelper.UpdateConfig();
                MessageBox.Show("添加完毕，生效的话，需要重新启动任务调度");
            }
            else
            {
                //新增
                //1.判断下
                if (configHelper.GetTask_config(Id.Text) != null)
                {
                    MessageBox.Show("ID应该是要唯一的，存在重复的任务");
                    return;
                }
                Ep_task_config task_Config = new Ep_task_config()
                {
                    Id = Id.Text,
                    IsEnabled = IsEnabled.SelectedValue.ToString(),
                    JobName = JobName.Text,
                    JobUrl = JobUrl.Text,
                    JsonString = JsonString.Text,
                    Metthod = Method.SelectedValue.ToString(),
                    TimeExpression = TimeExpression.Text,
                    TimeType = TimeType.Text,
                };
                configHelper.AddConfig(task_Config);
                MessageBox.Show("添加完毕，生效的话，需要重新启动任务调度");
            }
            RefreshConfigTree();
            ClearInput();
        }
    }
}
